<template>
  <div class="design-header-page">
    <!-- 顶部操作栏 -->
    <ul class="design-header">
      <div class="left">
        <li @click="handleInsertDataSource">数据源</li>
        <li @click="handleOpenDataSetDrawer">
          <i class="iconfont icon-a-icon-Dataset"></i>
          数据集
        </li>

        <li class="resolving-power">
          <i class="iconfont icon-icon-resolution"></i>
          <p>分辨率:</p>
          <el-select
            v-model="resolvingPower"
            popper-class="setSelect"
            placeholder="Select"
            @change="handleSelectResolvingChange"
            ref="customSelectRef"
          >
            <el-option
              v-for="item in resolvingPowerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
              <div v-if="item.label === '自定义'" class="el-option-slot-area">
                <div class="el-option-slot">
                  <span>自定义分辨率</span>
                  <el-button
                    text
                    @click="handleCloseCustomSelect"
                    :disabled="custom?.some((item) => item === '')"
                    >确定</el-button
                  >
                </div>
                <div>
                  横向:
                  <el-input
                    v-model="custom[0]"
                    @input="custom[0] = custom[0].replace(/[^\d]/g, '')"
                    placeholder="请输入横向分辨率"
                  />
                </div>
                <div>
                  纵向:
                  <el-input
                    v-model="custom[1]"
                    @input="custom[1] = custom[1].replace(/[^\d]/g, '')"
                    placeholder="请输入纵向分辨率"
                  />
                </div>
              </div>
              <span style="float: left" v-else>{{ item.label }}</span>
            </el-option>
          </el-select>
        </li>
      </div>
      <div class="center">
        <li @click="handleInsertComponent">
          <i class="iconfont icon-icon-insert"></i> 插入
        </li>

        <li @click="handleSetComponentGroup">
          <i class="iconfont icon-icon-component"></i>
          组件
        </li>

        <li @click="handleGlobalLinkageSetting">
          <i class="iconfont icon-icon-linkage"></i>
          联动
        </li>
        <li @click="handleSetBg">
          <i class="iconfont icon-icon-picture"></i>
          背景
        </li>
        <li @click="handleGlobalPenetrationSetting">
          <i class="iconfont icon-icon-penetrate"></i>
          穿透
        </li>

        <li class="compo-text-align">
          <!-- 文字对齐 -->
          <i class="iconfont" :class="currentTextAlign"></i>

          <el-select
            v-model="textAlign"
            placeholder=""
            @change="handleTextAlignChange"
          >
            <el-option
              v-for="item in textAlignOptions"
              :key="item.value"
              :label="item.content"
              :value="item"
            >
              <i :class="item.label" class="iconfont"></i>
            </el-option>
          </el-select>
        </li>
        <li class="compo-text-align">
          <!-- 组件对齐 -->
          <i class="iconfont" :class="currentCompoAlign"></i>

          <el-select
            v-model="compoTextAlign"
            placeholder=""
            @change="handleCompoAlignChange"
            style="width: 1.6rem"
          >
            <el-option
              v-for="item in compoTextAlignOptions"
              :key="item.value"
              :label="item.content"
              :value="item"
            >
              <i :class="item.label" class="iconfont"></i>
            </el-option>
          </el-select>
        </li>
      </div>
      <div>
        <el-button text @click="handleDeleteListOne">
          <i class="iconfont icon-icon-delete"></i>
          删除</el-button
        >
        <el-button text @click="handleSaveCanvas">
          <i class="iconfont icon-icon-file"></i>

          保存</el-button
        >
        <el-button type="primary" @click="handleSee">预览</el-button>
      </div>
    </ul>
    <hb-select-person
      :options="selectPersonOptions"
      v-if="showHbSelectPerson"
    />
    <!-- 数据源 -->
    <!-- <el-dialog v-model="dataSourceDialog" title="添加数据源"> -->
    <bi-dialog
      :width="'7.2rem'"
      :title="'添加数据源'"
      :showFooter="true"
      v-model:isShow="dataSourceDialog"
      :handlerSubmit="handlerDataSourceSubmit"
    >
      <data-source ref="dataSourceRef" v-if="dataSourceDialog"> </data-source>
      <!-- <div class="dialog-footer">
            <el-button @click="dataSourceDialog = false">取消</el-button>
            <el-button type="primary" @click="handleCancelDataSourceCheck"> 确定 </el-button>
        </div> -->
    </bi-dialog>

    <!-- 数据集配置 -->
    <bi-drawer v-model:drawer="dataSetDrawer" :show-close="false">
      <template #header>
        <div class="date-set-config-title">
          数据集配置
          <el-tooltip
            class="box-item"
            effect="dark"
            content="数据集指大屏内每个组件所包含的数据集合"
            placement="right-start"
          >
            <i class="iconfont icon-prompt"></i>
          </el-tooltip>
        </div>
      </template>
      <div class="date-set-operate-area">
        <div class="notice">已创建{{ dataSetList?.length }}个数据集</div>
        <div>
          <el-button
            @click="handleDeleteDateSetMore"
            :disabled="!dateSetCheckList.length"
            >删除</el-button
          >
          <el-button type="primary" @click="handleAddDataSet" :icon="Plus">
            添加数据集
          </el-button>
        </div>
      </div>

      <bi-dialog
        v-model:isShow="dataSetDialog"
        :title="'数据集'"
        width="7rem"
        class="report-config"
        :showFooter="true"
        :handlerSubmit="handlerDataSetSubmit"
      >
        <data-set ref="dataSetRef"></data-set>
      </bi-dialog>
    </bi-drawer>

    <!-- 组件组合配置 -->
    <!-- <el-drawer class="screen-set" v-model="componentsDrawer" title="组件" direction="rtl"> -->
    <bi-drawer
      v-model:drawer="componentsDrawer"
      title="组件"
      :show-close="true"
    >
      <component-combination ref="myRefs" v-if="componentsDrawer" />
    </bi-drawer>

    <!-- 组件总的联动 -->
    <bi-drawer v-model:drawer="globalLinkageDrawer" :show-close="false">
      <!-- <el-drawer class="screen-set" v-model="globalLinkageDrawer" title="联动设置" direction="rtl"> -->
      <template #header>
        <div>
          联动
          <el-tooltip
            class="box-item"
            effect="dark"
            content="通过单击图表中的某一个值、数字组件、文字组件、图片、下拉选值联动其他组件的值内容发生变化"
            placement="right-start"
          >
            <i class="iconfont icon-prompt"></i>
          </el-tooltip>
        </div>
      </template>
      <global-linkage />
    </bi-drawer>
    <!-- style="red;width:0.4rem;height:0.4rem;zIndex:999999;position:absolute;right: 6.4rem;" -->
    <!-- 组件总的穿透 -->

    <div
      @click="handleCloseChildrenDrawer"
      class="child-close-icon"
      v-if="showChildCloseIcon"
    >
      <!-- 关闭子集的穿透 -->
      <!-- <el-icon><CloseBold /></el-icon> -->
    </div>

    <!-- <el-drawer class="screen-set" v-model="globalPenetrationDrawer" title="穿透设置" direction="rtl"> -->
    <bi-drawer v-model:drawer="globalPenetrationDrawer" :show-close="false">
      <template #header>
        <div>
          穿透设置
          <el-tooltip
            class="box-item"
            effect="dark"
            content="通过双击图表中的某一个值、数字组件、表格行数据后使用弹出框展示该数值、数据是由哪几条数据构成"
            placement="right-start"
          >
            <i class="iconfont icon-prompt"></i>
          </el-tooltip>
        </div>
      </template>

      <global-penetration ref="globalPenetrationRef" />
    </bi-drawer>

    <!-- 画布背景  -->
    <bi-dialog
      :width="'5.2rem'"
      :title="'设置背景'"
      :showFooter="true"
      v-model:isShow="bgDialog"
      :handlerSubmit="handleScreenSetSubmitForm"
    >
      <el-form
        ref="screenSetRuleFormRef"
        :model="bgFormData"
        label-position="top"
        :require-asterisk-position="'right'"
        class="bg-form"
      >
        <el-form-item
          label="上传背景"
          prop="bgImgUrl"
          :rules="[{ required: true, message: '请上传背景图' }]"
        >
          <el-upload
            class="bg-upload"
            :action="global.httpUrl + '/cus/v1/fileTools/uploadSingleFile'"
            :show-file-list="false"
            :on-success="handleBgUploadSuccess"
          >
            <!-- <el-button type="primary">Click to upload</el-button> -->
            <el-input v-model.trim="bgFormData.bgImgUrl" clearable>
              <template #append> ... </template>
            </el-input>
          </el-upload>
        </el-form-item>
      </el-form>
    </bi-dialog>
  </div>
</template>

<script setup>
import { ref, watch, toRefs, computed, inject, provide } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, CloseBold, Search } from "@element-plus/icons-vue";

import DataSource from "@/views/design-center/components/data-source";
import DataSet from "@/views/design-center/components/data-set";

import ComponentCombination from "./component-combination";
import BiDrawer from "@/components/bi-drawer/main";

import GlobalLinkage from "./global-linkage";
import GlobalPenetration from "./global-penetration";
import {
  resolvingPowerOptions,
  compoTextAlignOptions,
  textAlignOptions,
} from "./constants";
import useComponentConfig from "@/views/design-center/store/component-config";
import { getIdAndEditIt } from "@/utils/common";
import { useAlign } from "@/hooks/use-align";
import { biMessage, biMessageBox } from "@/utils/use-message";

import { saveScreenApi } from "@/views/design-center/api/screen";

import {
  getScreenHaveConfigDataSetListApi,
  deleteDataSetOneApi,
} from "@/views/design-center/api/data-set";
import { useRoute } from "vue-router";
import useSelectPerson from "@/hooks/use-select-person";
import { log } from "@antv/g2plot/lib/utils";
const { selectPersonOptions } = useSelectPerson();

const showHbSelectPerson = ref(false);
const router = useRouter();
const route = useRoute();

const useComponentConfigStore = useComponentConfig();
const { currentCompoId, pageConfig } = toRefs(useComponentConfigStore);

const { currentCompoAlign, handleCompoAlignChange } = useAlign();

const global = inject("global");

const globalPenetrationRef = ref();

const dataSourceRef = ref();

const handleCloseChildrenDrawer = () => {
  console.log(111111111, globalPenetrationRef.value);
  globalPenetrationRef.value.addAndEditPenetrationDrawer = false;
};

const showChildCloseIcon = computed(() => {
  return globalPenetrationRef.value?.addAndEditPenetrationDrawer;
});

// const props = defineProps({
//   canvasPageConfig: {
//     type: Object,
//     default: () => {
//       return {};
//     }
//   }
// });

const currentTextAlign = ref("icon-a-icon-Left-aligntext");

const resolvingPower = ref("1920*1080");

const dataSourceDialog = ref(false);

const dataSetDrawer = ref(false); //是否展示数据集抽屉

const dataSetList = ref([]); //数据集配置后的list

const screenDrawer = ref(false); //是否展示主子屏设置抽屉

const componentsDrawer = ref(false); //是否展示主子屏设置抽屉

const dataSetDialog = ref(false); //数据集弹框

const screenSetRuleFormRef = ref();
const bgDialog = ref(false); //背景图设置

const bgFormData = ref({}); //背景图设置

const dateSetCheckList = ref([]);

const textAlign = ref({
  label: "icon-a-icon-Left-aligntext",
  value: "left",
  content: "左对齐",
}); //文字对齐
const compoTextAlign = ref({
  label: "icon-a-icon-Leftalign",
  value: "left",
  content: "左对齐",
}); //组件对齐

const globalLinkageDrawer = ref(false);

const globalPenetrationDrawer = ref(false);

const myRefs = ref();

const initDataSetId = ref({}); //修改的时候数据集的初始值

const custom = ref(["", ""]); //自定义宽*高
const customSelectRef = ref();

const emit = defineEmits([
  "open-insert-drawer",
  "delete-one-compo",
  "update-page-config",
]);

watch(
  () => componentsDrawer.value,
  (nv) => {
    if (!nv) {
      useComponentConfigStore.pageConfig.list = myRefs.value.treeData;
      console.log("组件组合配置抽屉关闭了------", myRefs.value.treeData);
    }
  }
);

/**
 * @description: 大屏预览
 * @return {*}
 */
const handleSee = () => {
  const newPage = router.resolve({
    name: "preview-screen", // 跳转的页面路由
    query: {
      bigScreenId: route.query.bigScreenId,
    },
  });
  window.open(newPage.href, "_blank"); // 打开新的窗口(跳转路径，跳转类型)
};

/**
 * @description: 保存画布的配置
 * @return {*}
 */
const handleSaveCanvas = async () => {
  // sessionStorage.setItem('pageConfig', JSON.stringify(props.canvasPageConfig)); //用于演示,调通后去掉
  // pageConfig.value.name = route.query.reportName;
  let res = await saveScreenApi({
    bigScreenId: route.query.bigScreenId,
    configStr: JSON.stringify(pageConfig.value),
    bigScreenName: route.query.bigScreenName,
  });

  if (res.code === 0) {
    // useComponentConfigStore.pageConfig = props.canvasPageConfig;
    biMessage("success", "保存成功");
    location.reload();
  }
  // sessionStorage.setItem('canvas', JSON.stringify(props.canvasPageConfig));
};

/**
 * @description:插入数据源
 * @return {*}
 */
const handleInsertDataSource = () => {
  dataSourceDialog.value = true;
};

/**
 * @description:打开数据集
 * @return {*}
 */
const handleOpenDataSetDrawer = () => {
  // emit('open-date-set-drawer', true);
  dataSetDrawer.value = true;
};
/**
 * @description:分辨率变化
 * @return {*}
 */
const handleSelectResolvingChange = (val) => {
  // console.log(val.split('*'), 111111111);
  useComponentConfigStore.pageConfig.w = val.split("*")?.[0];
  useComponentConfigStore.pageConfig.h = val.split("*")?.[1];
};

/**
 * @description: 插入组件
 * @return {*}
 */
const handleInsertComponent = () => {
  emit("open-insert-drawer", true);
};

/**
 * @description: 主子屏设置
 * @return {*}
 */
const handleOpenScreenDrawer = () => {
  screenDrawer.value = true;
};

/**
 * @description:设置画布背景
 * @return {*}
 */
const handleSetBg = () => {
  // debugger;
  bgDialog.value = true;
};

//获取已经配置的大屏数据集列表
const getScreenHaveConfigDataSetList = async () => {
  let res = await getScreenHaveConfigDataSetListApi({
    reportId: route.query.id,
  });
  dataSetList.value = res.data;
};

watch(
  () => dataSetDrawer.value,
  (nv) => {
    nv && getScreenHaveConfigDataSetList();
  }
);
watch(
  () => dataSetDialog.value,
  (nv) => {
    !nv && getScreenHaveConfigDataSetList();
  }
);

const dataSetRef = ref(null);
/**
 * @description:提交数据集
 * @param {*} data
 * @return {*}
 */
const handlerDataSetSubmit = () => {
  console.log(dataSetRef.value.submit, 33333333);
  dataSetRef.value.submit();
};

/**
 * @description:更新数据集展示list
 * @param {*} data
 * @return {*}
 */
const handleUpDateDataSet = (data) => {
  dataSetDialog.value = false;
  getScreenHaveConfigDataSetList();

  // console.log('更新数据集展示list ', data, dataSetList.value);
};

/**
 * @description:删除数据集配置回显的list
 * @return {*}
 */
const handleDeleteDateSetMore = async () => {
  let noticeRes = await biMessageBox(
    "warning",
    "",
    "是否删除当前数据集，删除后会影响当前绑定的组件展示"
  );

  let res = await (noticeRes && deleteDataSetOneApi(dateSetCheckList.value));
  if (res.code === 0) {
    biMessage("success", "删除成功");
    getScreenHaveConfigDataSetList();
  }
};

/**
 * @description:删除数据集单个删除
 * @param {*} setItem
 * @param {*} index
 * @return {*}
 */
const handleDeleteDateSetItem = async (setItem, index) => {
  let noticeRes = await biMessageBox(
    "warning",
    "",
    "是否删除当前数据集，删除后会影响当前绑定的组件展示"
  );

  let res = await (noticeRes && deleteDataSetOneApi([setItem.id]));
  if (res.code === 0) {
    biMessage("success", "删除成功");
    getScreenHaveConfigDataSetList();
  }
};

/**
 * @description: 设置组件分组
 * @return {*}
 */
const handleSetComponentGroup = () => {
  componentsDrawer.value = true;
};

/**
 * @description:画布背景图上传
 * @param {*} response
 * @param {*} uploadFile
 * @return {*}
 */
const handleBgUploadSuccess = (response, uploadFile) => {
  bgFormData.value.bgImgUrl = response.data;
  console.log(response.data, uploadFile);
};
/**
 * @description:上传背景图取消重置
 * @return {*}
 */
const handleScreenSetResetForm = (formEl) => {
  bgDialog.value = false;
  if (!formEl) return;
  formEl.resetFields();
};
/**
 * @description:上传背景图提交
 * @return {*}
 */
const handleScreenSetSubmitForm = async (formEl) => {
  let valid = await screenSetRuleFormRef.value.validate().catch(() => false);
  console.log(valid);

  if (valid) {
    console.log(bgFormData.value, "背景图值");
    // emit('update-page-config', bgFormData.value.bgImgUrl);
    useComponentConfigStore.pageConfig.bgImgUrl = bgFormData.value.bgImgUrl;
    bgDialog.value = false;
  }
};

/**
 * @description: 添加数据集
 * @return {*}
 */
const handleAddDataSet = () => {
  dataSetDialog.value = true;
  reportConfigType.value = "add";
};

const reportConfigType = ref(""); //是不是修改数据集配置
/**
 * @description:编辑数据集
 * @param {*} setItem
 * @param {*} index
 * @return {*}
 */
const handleEditDateSetItem = (setItem, index) => {
  console.log(setItem, 1111111111111);
  dataSetDialog.value = true;
  initDataSetId.value = setItem.id;
  reportConfigType.value = "edit";
};

/**
 * @description:删除画布中配置的组件
 * @return {*}
 */
const handleDeleteListOne = () => {
  emit("delete-one-compo");
};
/**
 * @description:总的联动配置页
 * @return {*}
 */
const handleGlobalLinkageSetting = () => {
  globalLinkageDrawer.value = true;
};

/**
 * @description:总的穿透配置
 * @return {*}
 */
const handleGlobalPenetrationSetting = () => {
  globalPenetrationDrawer.value = true;
};

/**
 * @description:分辨率的自定义功能
 * @return {*}
 */
const handleCloseCustomSelect = () => {
  resolvingPower.value = custom.value.join("*");
  useComponentConfigStore.pageConfig.w = custom.value[0];
  useComponentConfigStore.pageConfig.h = custom.value[1];
  customSelectRef.value.visible = false;
};

const handleTextAlignChange = (item) => {
  console.log(item.value, currentCompoId.value);
  currentTextAlign.value = item.label;
  getIdAndEditIt(pageConfig.value.list, currentCompoId.value, "styles", {
    textAlign: item.value,
  });
};
const handlerDataSourceSubmit = async () => {
  // console.log(dataSourceRef.value.$refs.jsonDataSourceRef.submit);
  dataSourceRef.value.$refs.jsonDataSourceRef.submit();

  // let res = await dataSourceRef.value.handleSubmitDataSourceCheck();
  // // console.log(res,55555555555555);
  // if (res) {
  //   dataSourceDialog.value = false;
  // }
};
provide("toFiveLinkageData", {
  reportConfigType: reportConfigType,
  initDataSetId: initDataSetId,
});
</script>

<style lang="scss">
.setSelect {
  .el-select-dropdown__item:last-child {
    height: 1.05rem;
  }

  .el-select-dropdown__item {
    padding: 0 0.06rem;
  }

  .el-button {
    color: #a8abb2 !important;
  }
}

.design-header-page {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
<style scoped lang="scss">
@import "../../styles/reset-select.scss";

.design-header {
  display: flex;
  height: 0.48rem;
  background: #fcfcfc;
  border-width: 1px 0px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.06);
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.04);
  align-items: center;
  padding: 0 0.28rem;

  .iconfont {
    margin-right: 0.08rem;
  }

  .left {
    display: flex;
    flex: 3;
    align-items: center;

    li {
      flex: 1;
    }

    .resolving-power {
      flex: 3;
      display: flex;
      align-items: center;

      :deep(.el-select) {
        width: 1.5rem;
      }
    }
  }

  .center {
    display: flex;
    flex: 5;
    align-items: center;

    li {
      padding: 0 0.2rem;
      // flex: 1;
    }
  }

  li {
    display: flex;
    align-content: center;
    cursor: pointer;
  }

  .compo-text-align {
    display: flex;
    align-items: center;

    :deep(.el-select) {
      width: 1.2rem;
    }
  }

  // 去掉el-select默认样式
  // :deep(.el-select .el-input__wrapper) {
  //     box-shadow: none !important;
  // }

  // :deep(.el-input .el-input__wrapper.is-focus) {
  //     box-shadow: none !important;
  // }
  // :deep(.el-select .el-input.is-focus .el-input__wrapper) {
  //     border-color: #dcdfe6 !important;
  //     box-shadow: none !important;
  // }
  // :deep(.el-input__inner:focus) {
  //     box-shadow: none !important;
  // }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  // margin-top: 0.3rem;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
}

:deep(.el-checkbox) {
  width: 100%;
}

:deep(.el-checkbox__label) {
  width: 100%;
}

.el-option-slot-area {
  width: 100%;
  padding: 0 0.06rem;

  :deep(.el-input) {
    width: 80%;
  }
}

.el-option-slot {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.bg-form {
  padding: 0 0.32rem;
}

.bg-upload {
  width: 100%;

  :deep(.el-upload) {
    width: 100%;
  }
}

.date-set-operate-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.16rem 0.24rem 0;

  .notice {
    color: #86909c;
  }
}

.date-set-list {
  padding: 0.16rem 0.24rem 0;
}

.date-set-list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-button {
    color: #165dff;
  }

  .el-checkbox-group {
    margin-bottom: 0.18rem;
  }
}

.report-config {
  position: relative;

  :deep(.el-dialog__body) {
    padding: 0 !important;
    // border-bottom: 0.01rem solid #e5e6eb;
  }
}
</style>
